package com.minshenglife.zanzan.web.weixin.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.minshenglife.zanzan.dao.BettingDao;
import com.minshenglife.zanzan.dao.IntegralDao;
import com.minshenglife.zanzan.dao.OperateLogDao;
import com.minshenglife.zanzan.dao.RedFlowerDao;
import com.minshenglife.zanzan.dao.UserDao;
import com.minshenglife.zanzan.entity.Betting;
import com.minshenglife.zanzan.entity.Review;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.Config;
import com.minshenglife.zanzan.pub.Keys;
import com.minshenglife.zanzan.pub.message.MessageUtil;
import com.minshenglife.zanzan.pub.message.WXRespMessage;
import com.minshenglife.zanzan.pub.message.custservice.CS_TextMessage;
import com.minshenglife.zanzan.result.RedFlowerResult;
import com.minshenglife.zanzan.service.ReviewService;


/**
 * 押宝专用包批处理service
 * @author huodd
 *
 */
@Component
@Transactional
public class WXBettingService {
	Logger log = LoggerFactory.getLogger(WXBettingService.class);
	@Resource
	private BettingDao bettingDao;
	@Resource
	RedFlowerDao flowerDao;
	@Resource
	OperateLogDao operateLogDao;
	@Resource
	private UserDao userDao;
	@Resource
	IntegralDao integralDao;
	@Resource
	ReviewService reviewService;
	@Resource
	WXAccTokenService tokenService;
	
	/**
	 * 批处理发送花王结果
	 */
	public void batchSendFlowerKingResult() {
		log.debug("start 批处理发送花王结果  开始运行。。。。。");
		String flowerKing=null;//花王
		String startDate="";
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Calendar c=Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, -1);
		startDate=sdf.format(c.getTime());
		try {
			//添加批处理日志，记录开始状态
			//获取昨日的花王
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("from", 0);
			map.put("to", 1);
				//设置查询的时间范围
			map.put("endDate", startDate);
			map.put("startDate", startDate);
			List<RedFlowerResult> rows =flowerDao.findRedFlowerRank(map);
			if(rows==null || rows.size()<=0 ){
				log.debug("获取花王失败,批处理终止");
				return ;
			}
			
			flowerKing=rows.get(0).getAddManId();
			log.debug(sdf.format(c.getTime())+"的花王是："+flowerKing);
			
			//获取昨日所有参与该游戏的人
			Map<String,Object> map1=new HashMap<String,Object>();
//			map1.put("byBetManId", flowerKing);
			map1.put("endDate", startDate);
			map1.put("startDate", startDate);
			map1.put("state", Keys.BETTING_STATE_ZERO);
			List<Betting> list=bettingDao.findBy(map1);
			if(list==null || list.size()<=0){
				log.debug("获取昨日所有参与该游戏的人——失败,批处理终止");
				return ;
			}
			String integralNum=Config.getProperty(Config.BETTING_WINNUM);
			log.debug("猜中花王的，奖励积分数："+integralNum);
			User King=userDao.getUserByUserId(flowerKing);
			//循环调用客服接口
			for(Betting bet : list){
				try {
					log.debug("开始给谁发送："+bet.getBetManId());
					//获取用户信息，发送中奖通知
					User user=userDao.getUserByUserId(bet.getBetManId());
//					String man=user.getEmp_name();
					
					String to_message="";
					//押宝人就是红花王
					if(flowerKing.equals(bet.getBetManId())){
						to_message="恭喜[亲]昨天在#谁是红花王#游戏中，" +
								"猜中红花王[自己]，特此奖励["+integralNum+"]积分！";
						//添加一条新鲜事
						Review review=new Review();
						review.setCriticsId(user.getEmpId());
						review.setByCriticsId(Keys.SYSTEM_SUPER_USER);//没有被评论对象，用系统管理员代替
						review.setReviewContent("["+user.getEmp_name()+"]昨天猜到了红花王["+King.getEmp_name()+"],得到["+integralNum+"]积分！");
						review.setCriticsType(Keys.REVIEW_CRITICS_TYPE_ZERO);
						review.setReviewType(Keys.REVIEW_TYPE_FIVE);
						reviewService.add(review);
					}
					//押宝人猜中了红花王
					else if(flowerKing.equals(bet.getByBetManId())){
						to_message="恭喜[亲]昨天在#谁是红花王#游戏中，" +
								"猜中红花王["+King.getEmp_name()+"]，特此奖励["+integralNum+"]积分！";
						//添加一条新鲜事
						Review review=new Review();
						review.setCriticsId(user.getEmpId());
						review.setByCriticsId(Keys.SYSTEM_SUPER_USER);//没有被评论对象，用系统管理员代替
						review.setReviewContent("["+user.getEmp_name()+"]昨天猜到了红花王["+King.getEmp_name()+"],得到["+integralNum+"]积分！");
						review.setCriticsType(Keys.REVIEW_CRITICS_TYPE_ZERO);
						review.setReviewType(Keys.REVIEW_TYPE_FIVE);
						reviewService.add(review);
					}
					//押宝人没有猜中红花王
					else{
						to_message="亲，很遗憾您没有猜中昨天的红花王["+King.getEmp_name()+"]！加油！";
					}
					
					CS_TextMessage tm=new CS_TextMessage();
					tm.setTouser(user.getWXCode());
					tm.setMsgtype(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
					tm.setText(to_message);
					WXRespMessage respMessage=WXBaseService.sendCustServiceMessage(tm,tokenService.getWXAccToken());
					log.info("==========="+respMessage.getErrcode());
					System.out.println("==========="+respMessage.getErrcode());
					if("0".equals(respMessage.getErrcode())){
						log.info("客服消息发送成功");
					}else{
						log.info("客服消息发送失败，错误信息："+respMessage.getErrmsg());
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.error("给"+bet.getBetManId()+"推送消息失败！");
				}
			}
			log.debug("批处理发送花王结果运行成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.debug("end 批处理发送花王结果  开始运行。。。。。");
	}
	
	public static void main(String[] asdf){
		String endDate="";
		String startDate="";
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Calendar c=Calendar.getInstance();
		endDate=sdf.format(c.getTime());
		c.add(Calendar.DAY_OF_MONTH, -1);
		startDate=sdf.format(c.getTime());
		System.out.println(endDate);;
		System.out.println(startDate);
	}
}
